package com.aoxin.controller.system;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.aoxin.model.system.SlfAttachment;
import com.aoxin.model.system.SlfAttachmentBiz;
import com.aoxin.service.inter.system.AttachmentBizService;
import com.aoxin.service.inter.system.AttachmentService;
import com.aoxin.util.AjaxRes;
import com.aoxin.util.Const;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.OSSUtils;
import com.aoxin.util.ThreadLocalUtil;
import com.aoxin.util.enumerate.OperateType;
import com.aoxin.util.log.LogInfo;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 附件 Controller
 * 
 * @author Melody
 * @date 2018年3月25日 下午2:57:54
 */
@Controller
@ResponseBody
@RequestMapping("/web/attachment")
public class AttachmentController {

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	private AttachmentBizService attachmentBizService;

	@RequestMapping("/uploadBiz")
	@LogInfo(content = "附件", operateType = OperateType.INSERT)
	public AjaxRes uploadBiz(SlfAttachmentBiz slfAttachmentBiz, @RequestParam("file") MultipartFile file, HttpServletRequest request, AjaxRes ajaxRes) {
		try {
			if (null == file) {
				ajaxRes.setFailMsg(ErrorUtil.NULL_FILE);
			} else if (file.getSize() > 1024 * 1024 * 10) {
				ajaxRes.setFailMsg(ErrorUtil.FILE_SIZE);
			} else {
				String path = request.getSession().getServletContext().getRealPath("attachment");
				String fileName = file.getOriginalFilename();
				// 添加附件业务
				slfAttachmentBiz = this.attachmentBizService.insertAttachmentBiz(slfAttachmentBiz);

				// 组装附件消息
				SlfAttachment attachment = new SlfAttachment();
				attachment.setAttachmentBizId(slfAttachmentBiz.getAttachmentBizId());
				attachment.setAttachmentName(fileName);
				attachment.setType(fileName.substring(fileName.lastIndexOf(".") + 1));
				attachment.setCreateDate(new Date());
				attachment.setCreater(ThreadLocalUtil.getEmployee().getEmployeeId());
				if (file.getSize() > 1024 * 1024) {
					attachment.setSize(file.getSize() / (1024 * 1024) + "MB");
				} else if (file.getSize() > 1024) {
					attachment.setSize(file.getSize() / 1024 + "KB");
				} else {
					attachment.setSize(file.getSize() + "B");
				}

				// 插件临时文件
				File tempFile = new File(path);
				if (!tempFile.getParentFile().exists()) {
					tempFile.getParentFile().mkdirs();
				}

				file.transferTo(tempFile);
				tempFile.delete();
				path = OSSUtils.upload(tempFile);

				attachment.setPath(path);
				// 添加附件
				attachment = this.attachmentService.insertAttachment(attachment);
				ajaxRes.setSucceed(attachment, Const.SAVE_SUCCEED);
			}

		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}

	@RequestMapping("/upload")
	@LogInfo(content = "附件", operateType = OperateType.INSERT)
	public AjaxRes upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, AjaxRes ajaxRes) {
		try {
			if (null == file) {
				ajaxRes.setFailMsg(ErrorUtil.NULL_FILE);
			} else if (file.getSize() > 1024 * 1024 * 1024) {
				ajaxRes.setFailMsg(ErrorUtil.FILE_SIZE);
			} else {
				String path = request.getSession().getServletContext().getRealPath("attachment");
				String fileName = file.getOriginalFilename();
				path += File.separator + fileName;
				// 组装附件消息
				SlfAttachment attachment = new SlfAttachment();
				attachment.setAttachmentBizId(null);
				attachment.setAttachmentName(fileName);
				attachment.setType(fileName.substring(fileName.lastIndexOf(".") + 1));
				attachment.setCreateDate(new Date());
				// attachment.setCreater(ThreadLocalUtil.getEmployee().getEmployeeId());
				if (file.getSize() > 1024 * 1024) {
					attachment.setSize(file.getSize() / (1024 * 1024) + "MB");
				} else if (file.getSize() > 1024) {
					attachment.setSize(file.getSize() / 1024 + "KB");
				} else {
					attachment.setSize(file.getSize() + "B");
				}
				String pathTemporaryStorage=path;
				if(path.contains(".png")){
					path=path.replace(".png", ".jpg");
				}
				// 插件临时文件
				File tempFile = new File(path);
				if (!tempFile.getParentFile().exists()) {
					tempFile.getParentFile().mkdirs();
				}
				file.transferTo(tempFile);
				try {
						Thumbnails.of(path).scale(1f).outputQuality(0.13f).outputFormat("jpg").toFile(tempFile);
						//压缩文件
						File tempFileCompress = new File(path);
						if (!tempFileCompress.getParentFile().exists()) {
							tempFileCompress.getParentFile().mkdirs();
						}
						path = OSSUtils.upload(tempFileCompress);
						tempFileCompress.delete();
					} catch (Exception e) {
						//处理异常上传原本文件      
						//TODO 待处理 初次加载时候回出错
					/*	File oldtempFile = new File(pathTemporaryStorage);
						if (!oldtempFile.getParentFile().exists()) {
							oldtempFile.getParentFile().mkdirs();
						}
						file.transferTo(oldtempFile);
						path = OSSUtils.upload(oldtempFile);
						oldtempFile.delete();*/
						e.printStackTrace();
					}
				tempFile.delete();
				attachment.setPath(path);
				// 添加附件
				attachment = this.attachmentService.insertAttachment(attachment);
				ajaxRes.setSucceed(attachment, Const.SAVE_SUCCEED);
			}

		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}

	/**
	 * 下载附件
	 * 
	 * @param bizIz
	 *            业务ID
	 * @param bizType
	 *            业务类型
	 */
	@RequestMapping("/download")
	public AjaxRes download(@RequestParam("attachmentId") Integer attachmentId, HttpServletResponse response, AjaxRes ajaxRes) {
		try {
			SlfAttachment slfAttachment = this.attachmentService.getAttachment(attachmentId);
			if (slfAttachment != null) {
				File file = new File(slfAttachment.getPath());
				if (file.exists()) {
					String fileName = new String(slfAttachment.getAttachmentName().getBytes("UTF-8"), "iso-8859-1");
					response.setContentType("application/force-download");// 设置强制下载不打开
					response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
					byte[] buffer = new byte[1024];
					FileInputStream fis = null;
					BufferedInputStream bis = null;
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					if (bis != null) {
						bis.close();
					}
					if (fis != null) {
						fis.close();
					}
				}
			}
		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
		return ajaxRes;
	}
}
